import { createSlice, PayloadAction} from '@reduxjs/toolkit';

import { StatePagingType } from 'storage/redux';
import RequestStatus from 'storage/redux/RequestStatus';
import {builderPagingHandler} from "storage/redux/reducer";
import {fetchAddUser, fetchDeleteUser, fetchUpdateUser, fetchUserPageData}
    from "storage/redux/async-action/userAsyncAction";
import UserStorage from "storage/local/UserStorage";

import {SecurityUser} from "type/entity/SecurityUser";


import LogFactory from "../../../log/LogFactory";

const log = LogFactory.getLogger("UserSlice");

/**
 * 用户状态管理类型
 */
export type UserState = StatePagingType<SecurityUser>

/** 状态初始化数据 */
const initialState: UserState = {
    data: [],
    loading: false,
    requestStatus: RequestStatus.INIT,
    currentPage: 1,
    pageSize: UserStorage.getInstance().getAdminPageConfigFromLocalStore().userPageSize,
    total: 0,
    totalPage: 10
};

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        login: (state, action: PayloadAction<any>) => {
            state = action.payload;
        }
    },
    extraReducers: (builder) => {
        builderPagingHandler(builder, fetchUserPageData);
        /** 添加用户信息 */
        builder.addCase(fetchAddUser.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
            // log.debug("添加用户信息成功", action.payload);
        });
        /** 修改用户信息 */
        builder.addCase(fetchUpdateUser.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
            log.debug("redux-修改用户信息成功", action.payload);
        });
        /** 删除用户信息 */
        builder.addCase(fetchDeleteUser.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
            // state.data = state.data.
            log.debug("redux-删除用户信息成功", action.payload);
        });
    }
});

export const {login} = userSlice.actions;
export default userSlice.reducer;
